package org.brownflat.lighthouse.util;


import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStream;

public class Log4jConfigurator {
    private static final Logger LOG = Logger.getLogger(Log4jConfigurator.class);
    private static String homePath = System.getenv("LIGHTHOUSE_HOME");

    static {
        System.setProperty("logfile.path", System.getenv("LIGHTHOUSE_HOME"));
    }

    public Log4jConfigurator() throws FileNotFoundException {
        init();
    }

    private void init() throws FileNotFoundException {
        DOMConfigurator configurator = new DOMConfigurator();
        File homeFile = new File(homePath + "/log4j.xml");
        if(homeFile.exists())  {
            FileReader fileReader = new FileReader(homeFile);
            configurator.doConfigure(fileReader, LogManager.getLoggerRepository());
            LOG.info("Logging configured from home location.");
        } else {
            InputStream stream = this.getClass().getResourceAsStream("/log4j.xml");
            configurator.doConfigure(stream, LogManager.getLoggerRepository());
            LOG.info("Logging configured from classpath.");
        }
    }
}